<template>
    <div>
        <div class="container">
            <el-button type="warning" :icon="CirclePlusFilled" style="margin-bottom: 10px" @click="visible = true">新增实收</el-button>
            <el-button type="danger" :icon="CirclePlusFilled" style="margin-bottom: 10px" @click="visibleFlow = true">新增应收</el-button>

        <el-table
          :data="tableData"
          :preserve-expanded-content="true"
          style="height: calc(100vh - 300px);"
          :cell-style="getCellStyle"
          row-key="id"
        :expand-row-keys="expandedRowKeys"
          @expand-change="handleExpandChange"
        >
          <el-table-column type="expand">
            <template #default="{ row}">
                <el-table :data="row.flows" class="no-header-bg" > 
                  <el-table-column label="实收水费(元)" prop="waterFeePayment" />    
                  <el-table-column label="实收电费(元)" prop="electricityFeePayment" />
                  <el-table-column label="实收总费用(元)" prop="totalFeePayment" />
                    <el-table-column label="操作" width="200px">
                        <template #default="{ row: flowRow }">
                                <el-button type="primary" size="small" :icon="Edit" @click="handleEditFlow(flowRow)">
                                    编辑
                                </el-button>
                                <el-button type="danger" size="small" :icon="Delete" @click="handleDeleteFlow(flowRow)">

                                    删除
                                </el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </template>
          </el-table-column>
          <el-table-column label="项目名称" prop="projectName" />
          <el-table-column label="选取月份" prop="billMonth" />
          <el-table-column label="应收水费(元)" prop="waterFee" />
          <el-table-column label="应收电费(元)" prop="electricityFee"  />
          <el-table-column label="应收总费用(元)" prop="totalFee" />
          <el-table-column label="实收总水费(元)" prop="waterFeePayment" />
          <el-table-column label="实收总电费(元)" prop="electricityFeePayment" />
          <el-table-column label="实收总费用(元)" prop="totalFeePayment" />
          <el-table-column label="最近录入时间" prop="updateTime" />
          <el-table-column label="操作" width="200px">
                <template #default="{ row: flowRow }">
                        <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(flowRow)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(flowRow)">
                            删除
                        </el-button>
                </template>
            </el-table-column>
          

        </el-table>
          <el-pagination v-if="hasPagination" :page-size="page.size" :background="false"
                         :page-sizes="[10, 20, 50, 100]"  @size-change="handleSizeChange"
                         layout="sizes,prev, pager, next" :total="page.total" @current-change="handleCurrentChange" style="margin-top: 10px" />
        </div>
        <el-dialog :title="isEdit ? '编辑应收记录' : '新增应收记录'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" />
        </el-dialog>
        <el-dialog :title="isEdit ? '编辑实收记录' : '新增实收记录'" v-model="visibleFlow" width="700px" destroy-on-close

            :close-on-click-modal="false" @close="closeFlowDialog">
            <TableEdit :form-data="rowDataFlow" :options="optionsFlow" :edit="isEdit" :update="updateFlowData" />
        </el-dialog>
        <el-dialog title="查看详情" v-model="visibleDetails" width="700px" destroy-on-close>

            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
        <el-dialog title="查看记录 详情" v-model="visibleFlowDetails" width="700px" destroy-on-close>
            <TableDetail :data="viewFlowData"></TableDetail>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="finance-management">

import { ref, reactive,onMounted,watch,nextTick } from 'vue';


import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { fetchBusinessProjectData,fetchUtilityData,saveUtilityData,saveUtilityRecordData,delUtilityDataById,delUtilityRecordById } from '@/api';
import TableDetail from '@/components/table-detail.vue';
import { Finance } from '@/types/dto';
import { FormOption, FormOptionList } from '@/types/form-option';
import { Delete, Edit, View, Refresh } from '@element-plus/icons-vue';

const hasPagination = ref(true);
const visible = ref(false);
const visibleFlow = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const rowDataFlow = ref({});

const expandedRowKeys = ref([]); // 用于控制展开行的数组


// 处理展开事件，更新 flowsArray 和 row.balance
const handleExpandChange = (row, expandedRows) => {
    expandedRowKeys.value = expandedRows.map(r => r.id); // 更新展开行的 keys


};

onMounted(async () => {
    const res = await fetchBusinessProjectData(1,1000);
    const opts = res.data.content.filter(item => item.selfProject === false) .map(item => ({
        label: item.projectName,
        value: item.projectName
    }));
    const projectItem = options.value.list.find(item => item.prop === 'projectName');
    if (projectItem) {
        projectItem.opts = opts;
    }
    const projectItemFlow = optionsFlow.value.list.find(item => item.prop === 'projectName');
    if (projectItemFlow) {
        projectItemFlow.opts = opts;
    }
    
});


const handleCurrentChange = (val: number) => {
    page.index = val;
    page.currentPage = val;
    getData();
};

const handleSizeChange = (val: number) => {
    page.size = val;
    page.index = 1;
    page.currentPage = 1;
    getData();
};

const page = reactive({
    total: 0,
    index: 1,
    size: 50,
    hasPagination: true,
    layout: 'prev, pager, next,total',
    currentPage: 1,
    pageCount: 1
})
const tableData = ref<[]>();
const getData = async () => {
    const res = await fetchUtilityData(page.index, page.size);
    tableData.value = res.data.content;
    page.index = res.data.number + 1;
    page.total = res.data.totalElements;
    page.size = res.data.size;
    page.pageCount = res.data.totalPages;
};

getData();


// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'select', prop: 'projectName', label: '项目名称' , required: true  },
        { type: 'month',format: 'YYYY-MM', prop: 'billMonth', label: '选取月份'  },
        { type: 'number', prop: 'waterFee', label: '应收水费(元)', required: true },
        { type: 'number', prop: 'electricityFee', label: '应收电费(元)', required: true },

    ]
})

// 新增/编辑记录弹窗相关
let optionsFlow = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'select', prop: 'projectName', label: '项目名称' , required: true  },
        { type: 'month',format: 'YYYY-MM', prop: 'billMonth', label: '选取月份'  },
        { type: 'number', prop: 'waterFeePayment', label: '实收水费(元)', required: true },
        { type: 'number', prop: 'electricityFeePayment', label: '实收电费(元)', required: true }

    ]
})

const handleEdit = (row) => {
    isEdit.value = true;
    visible.value = true;
    rowData.value = { ...row };
    
};

const handleEditFlow = (row) => {
    isEdit.value = true;
    visibleFlow.value = true;
    rowDataFlow.value = { ...row };
};



const updateData = async (data) => {
    await saveUtilityData(data);
    if (!isEdit.value) {
        ElMessage.success('新增成功');
    } else {
        ElMessage.success('编辑成功');
    }
    closeDialog();
    getData();
};

const updateFlowData = async (data) => {
    await saveUtilityRecordData(data);
    if (!isEdit.value) {
        ElMessage.success('新增记录成功');
    } else {
        ElMessage.success('编辑记录成功');
    }
    closeFlowDialog();
    getData();
};

const getCellStyle = ({ row, column, rowIndex, columnIndex }) => {
    // 应收字段和对应的实收字段映射
    const receivableToReceivedMap = {
        'waterFee': 'waterFeePayment',
        'electricityFee': 'electricityFeePayment',
        'totalFee': 'totalFeePayment'
    };
    
    // 实收字段和对应的应收字段映射（反向映射）
    const receivedToReceivableMap = {
        'waterFeePayment': 'waterFee',
        'electricityFeePayment': 'electricityFee',
        'totalFeePayment': 'totalFee'
    };
    
    // 检查是否为应收字段
    if (receivableToReceivedMap[column.property]) {
        const receivedProp = receivableToReceivedMap[column.property];
        
        if (receivedProp && row[receivedProp] !== undefined) {
            const receivable = parseFloat(row[column.property]) || 0;
            const received = parseFloat(row[receivedProp]) || 0;
            
            if (receivable > received) {
                console.log(`应收${column.property} > 实收${receivedProp}，应用红色样式`);
                return {
                    color: '#f56c6c',
                    fontWeight: 'bold'
                };
            } else if (received >= receivable) {
                console.log(`实收${receivedProp} >= 应收${column.property}，应用绿色样式`);
                return {
                    color: '#67c23a',
                    fontWeight: 'bold'
                };
            }
        }
    }
    
    // 检查是否为实收字段
    if (receivedToReceivableMap[column.property]) {
        const receivableProp = receivedToReceivableMap[column.property];
        
        if (receivableProp && row[receivableProp] !== undefined) {
            const receivable = parseFloat(row[receivableProp]) || 0;
            const received = parseFloat(row[column.property]) || 0;
            
            if (received < receivable) {
                console.log(`实收${column.property} < 应收${receivableProp}，应用红色样式`);
                return {
                    color: '#f56c6c',
                    fontWeight: 'bold'
                };
            } else if (received >= receivable) {
                console.log(`实收${column.property} >= 应收${receivableProp}，应用绿色样式`);
                return {
                    color: '#67c23a',
                    fontWeight: 'bold'
                };
            }
        }
    }
    
    return {};
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

const closeFlowDialog = () => {
    visibleFlow.value = false;
    isEdit.value = false;
};

// 查看详情弹窗相关
const visibleDetails = ref(false);
const visibleFlowDetails = ref(false);
const viewFlowData = ref({
    row: {},
    list: []
});
const viewData = ref({
    row: {},
    list: []
});


// 删除记录

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            await delUtilityDataById(row.id);
            await getData();
            ElMessage.success('删除成功');
        })
        .catch(() => { });
    
};

const handleDeleteFlow = async (row) => {
    
    await delUtilityRecordById(row.id);
    await getData();
}

</script>

<style>

.container {
    min-height: calc(100vh - 150px) !important; 
    box-sizing: border-box;
    background: #fff;
    padding: 20px;
    overflow: auto;
}

.el-table.no-header-bg th {
    height: 40px;
    background-color: #fff !important;
    font-weight: normal;
    text-align: center !important;

}
.el-table th.el-table__cell  {
    text-align: center !important;
}

.el-table td.el-table__cell{
    text-align: center !important;
}

/* 增强样式优先级 */
.el-table .warning-cell,
.el-table .el-table__cell.warning-cell {
    color: #f56c6c !important;
    font-weight: bold !important;
}

</style>